using System;
using System.Collections;
using System.Collections.Generic;
using SciptableObject;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using Utilities;
using EventHandler = Utilities.EventHandler;
using Random = UnityEngine.Random;
using SoundName=Utilities.SoundName;

public class AudioManager : Singleton<AudioManager>
{
    [Header("音乐数据库")]
    public SoundDetailsList_SO soundDetailsData;
    public AudioMixer audioMixer;
    public AudioSource gameSource;
    public AudioMixerSnapshot normalSnapShot;
    public float MusicStartSecond => Random.Range(1f, 3f);  
    
    private Coroutine soundRoutine;
    
    

    private void OnEnable()
    {
        EventHandler.PlaySoundEvent += OnPlaySoundEvent;
        EventHandler.GameDataValueSend += PlayQuestSound;
    }

    private void PlayQuestSound(List<EventRewordData> arg1, bool arg2)
    {
        if (arg2)
        {
            EventHandler.CallPlaySoundEvent(SoundName.QuestCompleted);
        }
        else
        {
            EventHandler.CallPlaySoundEvent(SoundName.QuestFail);
        }
    }

    private void OnDisable()    
    {
        EventHandler.PlaySoundEvent -= OnPlaySoundEvent;
    }
    
    private void OnPlaySoundEvent(SoundName soundName) //呼叫PoolManager载入音效
    {
        var soundDetails = soundDetailsData.GetSoundDetails(soundName);
        if (soundDetails != null)
            EventHandler.CallInitSoundEffect(soundDetails);
    }

    public void Start()
    {
        SoundDetails music = soundDetailsData.GetSoundDetails(SoundName.music);
        // soundRoutine = StartCoroutine(PlaySoundRoutine(music));
    }

    /// <summary>
    /// 播放背景音乐
    /// </summary>
    /// <param name="soundDetails"></param>
    private void PlayMusicClip(SoundDetails soundDetails, float transitionTime)
    {
        gameSource.clip = soundDetails.soundClip;
        if (gameSource.isActiveAndEnabled)
            gameSource.Play();

        normalSnapShot.TransitionTo(transitionTime);
    }
    private float ConvertSoundVolume(float amount)
    {
        return (amount * 100 - 80);
    }
    // private IEnumerator PlaySoundRoutine(SoundDetails music)
    // {
    //     if (music != null )
    //     {
    //         yield return new WaitForSeconds(1f);
    //         PlayMusicClip(music, musicTransitionSecond);
    //     }
    // }
}
